package com.security.springmvc.controller;

import com.security.springmvc.model.AuthenticationRequest;
import com.security.springmvc.model.UserDto;
import com.security.springmvc.service.AuthenticationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@RestController
public class LoginController {

    @Autowired
    AuthenticationService authenticationService;

    @RequestMapping(value = "/login")
    public void login(AuthenticationRequest authenticationRequest, HttpServletResponse response, HttpSession session) throws IOException {
        UserDto userDto = authenticationService.authenticate(authenticationRequest);
        String result = userDto.getFullname() + " 登录成功!";

        // 保存到session
        session.setAttribute(UserDto.SESSION_USER_KEY, userDto);

        // 设置响应内容
        response.setContentType("text/plain;charset=UTF-8");
        response.getWriter().write(result);
    }

    @RequestMapping(value = "/logout")
    public void logout(HttpSession session,HttpServletResponse response) throws IOException {
        session.invalidate();
        response.setContentType("text/plain;charset=UTF-8");
        response.getWriter().write("注销成功!");
    }

    @RequestMapping(value = "/r/r1")
    public void r1(HttpSession session,HttpServletResponse response) throws IOException {
        UserDto user = (UserDto) session.getAttribute(UserDto.SESSION_USER_KEY);
        String result = "";
        if(user != null) {
            result =  "Hello " + user.getFullname() + "! 欢迎访问资源1!";
        }else {
            result =  "请先登录!";
        }
        // 设置响应内容
        response.setContentType("text/plain;charset=UTF-8");
        response.getWriter().write(result);
    }

    @RequestMapping(value = "/r/r2")
    public void r2(HttpSession session,HttpServletResponse response) throws IOException {
        UserDto user = (UserDto) session.getAttribute(UserDto.SESSION_USER_KEY);
        String result = "";
        if(user != null) {
            result =  "Hello " + user.getFullname() + "! 欢迎访问资源2!";
        }else {
            result =  "请先登录!";
        }
        // 设置响应内容
        response.setContentType("text/plain;charset=UTF-8");
        response.getWriter().write(result);
    }
}
